package com.jl.controller;

import com.jl.thread.BeanComponents;
import com.jl.thread.ThreadDtoUtils;
import com.jl.utils.WebDriverUtils;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : ljl
 * @date : 10:13 2021/1/6
 */
@Slf4j
@Controller
@RequestMapping("/spider")
public class SpiderController {

    @Autowired
    private BeanComponents beanComponents;

    @Autowired
    private ThreadDtoUtils threadDtoUtils;

    @GetMapping("/test")
    @ResponseBody
    public String test(String name) {
        return name;
    }

    @GetMapping("/start")
    @ResponseBody
    public void start() throws Exception {
        WebDriver driver = null;
        try {
            //谷歌插件存放路径，版本：87.0.4280.88
            String path = "spider-server/tools/chromedriver.exe"
                    // 登录页面url
                    , loginUrl = "https://kyfw.12306.cn/otn/resources/login.html"
                    // 车票列表url
                    , indexUrl = "https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc";
            //初始化谷歌游览器
            driver = WebDriverUtils.initChromeDriver(path);
            // 登录
            WebDriverUtils.login(driver, loginUrl);
            //出发地
            String startSite = "深圳北"
                    //目的地
                    , endSite = "郴州西"
                    //出发日期 如: 20, 15
                    , startDate = "6";
            // monthType:本月还是次月,0本月,1次月;count:查询次数计数
            int monthType = 1, count = 0;
            if (WebDriverUtils.isDisplay(driver, By.className("modal"))) {
                // 重新创建一个无头模式driver
                driver = WebDriverUtils.initHeadleChromeDriver(driver, path);
                for (int i = 0; i < 3; i++) {
//                while (true){
                    count++;
                    log.info("====================第{}次查询车票", count);
                    //进入车票列表页面
                    driver.get(indexUrl);
                    // 检查是否有弹出消息，有的话关闭
                    if (WebDriverUtils.isElementExist(driver, By.id("content_defaultwarningAlert_id"))) {
                        driver.findElement(By.id("gb_closeDefaultWarningWindowDialog_id")).click();
                    }
                    // 查询车票任务
                    driver = WebDriverUtils.seekTicket(driver, startSite, endSite, startDate, monthType);
                    // 判断车票列表是否加载成功
                    if (WebDriverUtils.isDisplay(driver, By.id("queryLeftTable"))) {
                        // 获取车票列表
                        List<WebElement> webElementList = WebDriverUtils.getTicketList(driver);
                        // 获取线程池
//                        ExecutorService executorService = beanComponents.executorService();
                        for (int j = 0; j < webElementList.size(); j++) {
                            /** 进入过其他页面页面元素过期所以需要二次获取  */
                            // 检查是否有弹出消息，有的话关闭
                            if (WebDriverUtils.isElementExist(driver, By.id("content_defaultwarningAlert_id"))) {
                                driver.findElement(By.id("gb_closeDefaultWarningWindowDialog_id")).click();
                                // 查询车票任务
                                driver = WebDriverUtils.seekTicket(driver, startSite, endSite, startDate, monthType);
                            }
                            // 判断车票列表是否加载成功
                            if (WebDriverUtils.isDisplay(driver, By.id("queryLeftTable"))) {
                                // 获取车票列表
                                webElementList = WebDriverUtils.getTicketList(driver);
                                List<WebElement> webElementsTd = webElementList.get(j).findElements(By.tagName("td"));
                                try {
                                    //多线程寻找车票
//                                threadDtoUtils.asynTickets(j, webElementsTd, driver, executorService);
                                    // 寻找车票
                                    WebDriverUtils.seekTickets(j, webElementsTd, driver);
                                } catch (Exception e) {
                                    String number = webElementsTd.get(0).findElement(By.tagName("a")).getText();
                                    log.error("==========车次：{},异常：{}", number, e.getMessage());
                                }
                            }

                        }
                    }
                    Thread.sleep(4000);
                }
            }
        } catch (Exception e) {
            log.error("==========初始化异常：{}", e.getMessage());
        } finally {
//            driver.quit();
        }
    }
}
